<?php

namespace App\Http\Controllers\V1;

use App\Models\User;
use App\Support\Code;
use Illuminate\Support\Str;
use App\Http\Requests\RegisterRequest;

class RegisterController extends ApiController
{
    public function index(RegisterRequest $request, User $user)
    {
        $user->name = $request->name;
        $user->nickname = $request->nickname;
        $user->password = $request->password;
        $user->invitation_code = $this->getInvitationCode(); // 获取邀请码
        if ($request->invitation_code) {
            $parentId = $this->getParentByCode($request->invitation_code);
            if ($parentId) {
                $user->parent_id = $parentId;
            } else {
                return $this->fail(Code::PARAMETER_ERROR, '邀请码错误！');
            }
        }

        [$user->wallet_address, $user->mnemonic_word] = $this->getWalletAddressAndMnemonicWord();
        
        $user->save();

        $token = $user->createToken('api')->accessToken;

        return $this->setMsg('注冊成功')->success([
            'name' => $user->name,
            'status' => $user->status,
            'token' => 'Bearer ' . $token,
            'mnemonic_word' => $user->mnemonic_word,
            'file' => storage_url('/vrts.apk'),
            'qrcode' => storage_url('/vrts.png')
        ]);
    }

    /**
     * @param $code
     * @return mixed|void
     */
    private function getParentByCode($code)
    {
        $user = User::where('invitation_code', $code)->first();
        if (!$user) {
            return;
        }
        return $user->id;
    }

    private function getInvitationCode()
    {
        do {
            $invitationCode = Str::random(6);
        } while (User::where('invitation_code', $invitationCode)->count());

        return $invitationCode;
    }

    private function getWalletAddressAndMnemonicWord()
    {
        $client = get_eth_client();

        $res = $client->post('/newAccount');
        $data = json_decode($res->getBody(), true)['data'];

        $walletAddress = $data['address'];
        $mnemonics = explode(' ', $data['mnemonic']);
        $mnemonicWord = implode(' ', array_slice($mnemonics, 0, 9));

        return [$walletAddress, $mnemonicWord];
    }
}
